package com.jiujiu.utitls;

import org.apache.commons.lang3.math.NumberUtils;

import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhaoJunZhou
 * @Date 2020/10/9
 * 继承序列化的接口：主要用途就是约定了序列化的接口方便代码转化为字节串，但是具体的序列化方法不依靠于此
 * --key1 value1 -key2 value2
 */
public class PropertyAnalysis implements Serializable {
    private static final long serialVersionUID = 1L;
    protected static final String NO_VALUE_KEY = "__NO_VALUE_KEY";
    protected static final String DEFAULT_UNDEFINED = "<undefined>";

    /**
     * 直接获取到传入的参数
     * @param args  获取到{@link com.jiujiu.Main#main(String[])} 传入的参数
     * @return
     */
    public static Map<String,String> fromArgs(String[] args){
        /*定义的初始化的大小反之对象初始值过大*/
        final Map<String, String> analysisMap = new HashMap<String, String>(args.length / 2);
        int i = 0;
        while (i < args.length) {
            final String key;
            if (args[i].startsWith("--")) {
                key = args[i].substring(2).toLowerCase();
            } else if (args[i].startsWith("-")) {
                key = args[i].substring(1).toLowerCase();
            } else {
                throw new IllegalArgumentException(
                        String.format("Error parsing arguments '%s' on '%s'. Please prefix keys with -- or -.",
                                Arrays.toString(args), args[i]));
            }
            if (key.isEmpty()) {
                throw new IllegalArgumentException(
                        "The input " + Arrays.toString(args) + " contains an empty argument");
            }
            i += 1; // try to find the value

            if (i >= args.length) {
                analysisMap.put(key, NO_VALUE_KEY);
            } else if (NumberUtils.isNumber(args[i])) {
                analysisMap.put(key, args[i]);
                i += 1;
            } else if (args[i].startsWith("--") || args[i].startsWith("-")) {
                // the argument cannot be a negative number because we checked earlier
                // -> the next argument is a parameter name
                analysisMap.put(key, NO_VALUE_KEY);
            } else {
                analysisMap.put(key, args[i]);
                i += 1;
            }
        }
        return analysisMap;
    }
}
